package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.service.user.AddressBookMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service("userAddressBookService")
@Slf4j
public class AddressBookServiceImpl implements AddressBookMapper {
    private final com.sky.mapper.AddressBookMapper addressBookMapper;

    @Autowired
    public AddressBookServiceImpl(com.sky.mapper.AddressBookMapper addressBookMapper) {
        this.addressBookMapper = addressBookMapper;
    }

    /**
     * 新增地址
     *
     * @param addressBook 地址实体类
     */
    public void saveAddress(AddressBook addressBook) {
        log.info("执行 新增地址 业务: {}",addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insertAddress(addressBook);
    }


    /**
     * 根据id删除地址
     *
     * @param addressId 地址Id
     */
    public void deleteAddressById(Long addressId) {
        log.info("执行 根据id删除地址 业务: {}",addressId);
        addressBookMapper.deleteAddressById(addressId);
    }


    /**
     * 根据id修改地址
     *
     * @param addressBook 地址实体类
     */
    public void updateAddress(AddressBook addressBook) {
        log.info("执行 根据id修改地址 业务: {}",addressBook);
        addressBookMapper.updateAddress(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook 地址实体类
     */
    @Transactional
    public void setDefaultAddress(AddressBook addressBook) {
        log.info("执行 设置默认地址 业务: {}",addressBook);
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAddressIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddress(addressBook);
    }

    /**
     * 条件查询地址
     *
     * @param addressBook 地址实体类
     * @return 地址实体类集合
     */
    public List<AddressBook> listAddress(AddressBook addressBook) {
        log.info("执行 条件查询地址 业务: {}",addressBook);
        return addressBookMapper.listAddress(addressBook);
    }



    /**
     * 根据id查询
     *
     * @param addressId 地址Id
     * @return 地址实体类
     */
    public AddressBook getAddressById(Long addressId) {
        log.info("执行 根据id查询 业务: {}",addressId);
        return addressBookMapper.getAddressById(addressId);
    }



}
